﻿using JinYuan.Helper;
using JinYuan.Models;
using Language;
using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmGroupConfig : MultiLanguageForm
    {
        public FrmGroupConfig(PLCConfig plc)
        {
            InitializeComponent();


            //this.cmb_StoreArea.DataSource = new string[] { "输入线圈", "输出线圈", "输入寄存器", "输出寄存器" };

            this.dgv_Main.AutoGenerateColumns = false;
            currentPlc = plc;
            TotalGroups = GetALLGroups();
            RefreshGroup();
        }

        private string groupPath = Application.StartupPath + "\\Config\\Group.xlsx";

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        #endregion


        private List<Group> TotalGroups = new List<Group>();
        private PLCConfig currentPlc;

        /// <summary>
        /// 获取所有通信组
        /// </summary>
        /// <returns></returns>
        private List<Group> GetALLGroups()
        {
            try
            {
                return MiniExcel.Query<Group>(groupPath).ToList();
            }
            catch (Exception)
            {

                return new List<Group>();
            }

        }

        /// <summary>
        /// 更新通信组集合
        /// </summary>
        private void RefreshGroup()
        {
            if (TotalGroups != null && TotalGroups.Count > 0)
            {
                this.dgv_Main.DataSource = null;
                this.dgv_Main.DataSource = TotalGroups;
            }
        }

        #region 无边框拖动
        private Point mPoint;
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }

        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
            }
        }
        #endregion


        /// <summary>
        /// 判断组名称是否存在
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        private bool IsGroupNameExits(string groupName)
        {
            return TotalGroups.FindAll(c => c.GroupName == groupName).ToList().Count < 0;
        }

        #region 增删改通信组
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Add_Click(object sender, EventArgs e)
        {
            string groupName = this.txt_GroupName.Text.Trim();
            if (groupName.Length == 0)
            {
                new FrmMsgBoxOutWithAck(2, "通信组名称不能为空！", "添加通信组").Show();
                return;
            }

            if (IsGroupNameExits(groupName))
            {
                new FrmMsgBoxOutWithAck(2, "通信组名称已存在！", "添加通信组").Show();
                return;
            }

            TotalGroups.Add(new Group()
            {
                GroupName = this.txt_GroupName.Text,
                Start = this.txtStart.Text,
                Length = Convert.ToUInt16(this.num_Length.Value),
                IsTiggerRead = this.ckb_IsTiggerRead.Checked ? true : false,
                IsFeedbackPlc = this.chk_IsFeedbackPlc.Checked ? true : false,
                IsActive = this.ckb_IsEnable.Checked ? true : false,
                Remark = this.txt_Remark.Text.Trim()
            });

            try
            {
                MiniExcel.SaveAs(groupPath, TotalGroups, overwriteFile: true);
                new FrmMsgBoxOutWithAck(1, "添加通信组成功", "添加通信组").Show();

                //刷新数据
                RefreshGroup();
            }
            catch (Exception ex)
            {
                new FrmMsgBoxOutWithAck(3, "添加通信组失败:" + ex.Message, "添加通信组").Show();
            }

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            string groupName = this.txt_GroupName.Text.Trim();

            if (IsGroupNameExits(groupName))
            {
                new FrmMsgBoxOutWithAck(2, "通信组名称不存在！", "删除通信组").Show();
                return;
            }

            TotalGroups.RemoveAll(c => c.GroupName == groupName);
            try
            {
                MiniExcel.SaveAs(groupPath, TotalGroups, overwriteFile: true);

                //刷新数据
                RefreshGroup();
            }
            catch (Exception ex)
            {

                new FrmMsgBoxOutWithAck(3, "删除通信组失败:" + ex.Message, "删除通信组").Show();
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Modify_Click(object sender, EventArgs e)
        {
            string groupName = this.txt_GroupName.Text.Trim();

            if (IsGroupNameExits(groupName))
            {
                new FrmMsgBoxOutWithAck(2, "通信组名称已存在！", "修改通信组").Show();
                return;
            }

            var group = TotalGroups.Find(c => c.GroupName == groupName);

            group.Start = this.txtStart.Text;
            group.Length = Convert.ToUInt16(this.num_Length.Value);
            group.IsTiggerRead = this.ckb_IsTiggerRead.Checked ? true : false;
            group.IsFeedbackPlc = this.chk_IsFeedbackPlc.Checked ? true : false;
            group.IsActive = this.ckb_IsEnable.Checked ? true : false;
            group.Remark = this.txt_Remark.Text.Trim();


            try
            {
                MiniExcel.SaveAs(groupPath, TotalGroups, overwriteFile: true);

                //刷新数据
                RefreshGroup();
            }
            catch (Exception ex)
            {

                new FrmMsgBoxOutWithAck(3, "修改通信组失败:" + ex.Message, "修改通信组").Show();
            }

        }

        #endregion

        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        /// <summary>
        /// 行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint((DataGridView)sender, e);
        }


        /// <summary>
        /// 默认为空显示特定字符
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                object value = this.dgv_Main.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

                if (value == null || value.ToString().Length == 0)
                {
                    e.Value = "---";
                }
                ;
            }
        }


        /// <summary>
        /// 选中行显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                UpdateGroup(TotalGroups[e.RowIndex]);
            }
        }

        private void UpdateGroup(Group group)
        {
            if (group != null)
            {
                this.txt_GroupName.Text = group.GroupName;
                this.txtStart.Text = group.Start;
                this.num_Length.Value = group.Length;
                this.ckb_IsTiggerRead.Checked = group.IsTiggerRead;
                this.chk_IsFeedbackPlc.Checked = group.IsFeedbackPlc;
                this.ckb_IsEnable.Checked = group.IsActive;
                this.txt_Remark.Text = group.Remark;
            }
        }
    }
}
